package com.shuzijun.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CombinationSumIi{
    public static void main(String[] args) {
         
         Solution solution = new CombinationSumIi().new Solution();
        
        
    }
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
        private ArrayList<List<Integer>> result = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < candidates.length; i++) {
            if (!map.containsKey(candidates[i])){
                map.put(candidates[i],1);
            }else {
                map.put(candidates[i], map.get(candidates[i]+1));
            }
        }

        ArrayList<Integer> nums = new ArrayList<>();
        ArrayList<Integer> counts = new ArrayList<>();
        for (int i = 0; i < candidates.length; i++) {
            if (map.containsKey(candidates[i])){
                nums.add(candidates[i] );
                counts.add(map.get(candidates[i]));
                map.remove(candidates[i]);
            }
        }

        backTrack(nums,counts,0,target,new ArrayList<>());
        return result;

    }

        private void backTrack(ArrayList<Integer> nums, ArrayList<Integer> counts, int k, int left, ArrayList<Object> path) {
            if (left == 0){
                result.add(new ArrayList(path));
                return;
            }
            if (left < 0 || k == nums.size()){
                return;
            }
            for (int count = 0; count <= counts.get(k); count++) {
                for (int i = 0; i < count; i++) {
                    path.add(nums.get(k));
                }
                backTrack(nums,counts,k+1,left-count* nums.get(k), path);
                for (int i = 0; i < count; i++) {
                    path.remove(path.size()-1);
                }
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}